package com.wswy.wyjk.core

import android.content.Context
import android.database.sqlite.SQLiteDatabase
import com.raft.framework.db.DBHelper
import com.raft.framework.utils.AssetUtils
import com.raft.framework.utils.RxUtils
import com.wswy.wyjk.AppContext
import com.wswy.wyjk.BuildConfig
import com.wswy.wyjk.db.JKDbHelper
import io.reactivex.Maybe
import io.reactivex.observers.ResourceMaybeObserver
import timber.log.Timber


object AppInitializer {

    private const val DB_WYJK = "wyjk_new_3.db"


    @JvmStatic
    fun init(context: Context){
        App.loadConfig()
        val dbFile = AppContext.getContext().getDatabasePath(DB_WYJK)

        //如果本地数据库不存在，直接复制
        val f = dbFile.exists()
        if (!f){
            Maybe.fromCallable {
                AssetUtils.copy(AppContext.getContext(),DB_WYJK,dbFile)

                //打开数据库
                App.daoSession = JKDbHelper(AppContext.getContext())
                true
            }.compose(RxUtils.io2main())
                .subscribe (object :ResourceMaybeObserver<Boolean?>(){
                    override fun onSuccess(t: Boolean) {
                        Timber.e("first init $t")
                    }

                    override fun onComplete() {}

                    override fun onError(e: Throwable) {
                        Timber.e(e)
                    }

                })
        }else{
            App.daoSession = JKDbHelper(AppContext.getContext())
        }
    }
}